<template>
    <div>
        <el-dialog v-model="state.uploadDialogVisible" width="80%" @close="state.uploadStutas = false">
            <div v-if="!state.uploadStutas">
                <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="state.headers" action="#"
                    :disabled="state.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess"
                    :auto-upload="false" :before-upload="beforeUpload" drag>
                    <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                    <div class="el-upload__tip text-center" slot="tip">
                        <span>仅允许导入xls、xlsx格式文件。</span>
                    </div>
                </el-upload>
            </div>
            <div v-if="state.uploadStutas">
                <el-table ref="multipleTableRef" :data="paginatedData" style="width: 100%">
                    <el-table-column prop="id" label="序号" width="150" align="center" />
                    <el-table-column prop="workOrderName" label="工单名称" align="center" />
                    <el-table-column prop="income" label="收入" align="center" />
                    <el-table-column prop="workOrderDescription" label="备注" align="center" />
                </el-table>

                <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="state.parsePage.pageNum" :page-sizes="[5, 10]" :page-size="state.parsePage.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="state.parsePage.total" class="mt-6">
                </el-pagination>
            </div>
            <div slot="footer" class="mt-2 flex flex-row-reverse">
                <el-button @click="state.uploadDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitFileForm" class="me-2">
                    {{ state.uploadStutas ? '导 入' : '确 定' }}
                </el-button>
            </div>
        </el-dialog>
        <!-- 详情 -->
        <el-drawer ref="drawerRef" v-model="state.detailDrawer" title="工单详情" :before-close="handleClose" direction="rtl">
            <el-row>
                <el-col :span="24" class="flex">
                    <div class="mr-4">工单号: </div>
                    <div>{{ state.detailData.OrderNumber }}</div>
                </el-col>
            </el-row>
            <el-row class="mt-4">
                <el-col :span="24" class="flex">
                    <div class="mr-4">工单名称: </div>
                    <div>{{ state.detailData.WorkOrderName }}</div>
                </el-col>
            </el-row>
            <el-row class="mt-4">
                <el-col :span="12" class="flex">
                    <div class="mr-4">状态:</div>
                    <el-tag v-if="state.detailData.DueDate < getDay()" type="danger">未完成</el-tag>
                    <el-tag :type="state.detailData.Status == '1' ? 'warn' : 'success'" v-else>
                        {{ state.detailData.Status == '1' ? '已完成' : '进行中' }}
                    </el-tag>
                </el-col>
                <el-col :span="12" class="flex">
                    <div class="mr-4">处理等级:</div>
                    <el-tag
                        :type="state.detailData.Level == '1' ? 'warning' : state.detailData.Level == '2' ? 'success' : 'danger'"
                        :effect="state.detailData.Level == '1' ? 'plain' : state.detailData.Level == '2' ? 'light' : 'dark'">
                        {{ state.detailData.Level == "1" ? "较低" : state.detailData.Level == "2" ?
                            "中等" : "紧急" }}
                    </el-tag>
                </el-col>
            </el-row>

            <el-row class="mt-4 flex items-center" v-if="state.detailData.CreatedUser">
                <el-col :span="12" class="flex item-center">
                    <div class="mr-4">创建人账号: </div>
                    <div class="flex">
                        <div>{{ state.detailData.CreatedUser.UserName }}</div>
                    </div>
                </el-col>
                <el-col :span="12" class="flex items-center">
                    <el-avatar :src='getAvatarUrl(state.detailData.CreatedUser.Avatar)'></el-avatar>
                </el-col>
            </el-row>
            <el-row class="mt-4 items-center" v-if="state.detailData.User">
                <el-col :span="12" class="flex item-center">
                    <div class="mr-4">接受人账号: </div>
                    <div class="flex">
                        <div>{{ state.detailData.User.UserName }}</div>
                    </div>
                </el-col>
                <el-col :span="12" class="flex items-center">
                    <el-avatar :src='getAvatarUrl(state.detailData.User.Avatar)'></el-avatar>
                </el-col>
            </el-row>

            <el-row class="mt-4">
                <el-col :span="24" class="flex">
                    <div class="mr-4">收入: </div>
                    <div>{{ state.detailData.Income }}</div>
                </el-col>
            </el-row>
            <el-row class="mt-4">
                <el-col :span="24" class="flex">
                    <div class="mr-4">备注: </div>
                    <div>{{ state.detailData.WorkOrderDescription }}</div>
                </el-col>
            </el-row>
            <el-row class="mt-4">
                <el-col :span="12" class="flex">
                    <div class="mr-4">审批人: </div>
                    <div>程封</div>
                </el-col>
                <el-col :span="12" class="flex">
                    <div class="mr-4">更新时间: </div>
                    <div>{{ state.detailData.Update }}</div>
                </el-col>
            </el-row>
            <el-row class="mt-4">
                <el-col :span="12" class="flex">
                    <div class="mr-4">创建时间: </div>
                    <div>{{ state.detailData.CreatedDate }}</div>
                </el-col>
                <el-col :span="12" class="flex">
                    <div class="mr-4">截止时间: </div>
                    <div>{{ state.detailData.DueDate }}</div>
                </el-col>
            </el-row>
        </el-drawer>
        <!-- 添加新增窗口 -->
        <el-dialog title="新增工单信息" v-model="state.addDialogVisible" width="50%" @close="state.editForm = {}">
            <el-form ref="addForm" :model="state.editForm" :rules="state.rules" label-width="80px">
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="工单名称" prop="workOrderName">
                            <el-input v-model="state.editForm.workOrderName"></el-input>
                        </el-form-item>

                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="收入" prop="income">
                            <el-input v-model="state.editForm.income"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="处理等级" prop="workOrderLevel">
                            <el-select v-model="state.editForm.workOrderLevel" placeholder="请选择">
                                <el-option v-for="item, index in state.statusList" :key="index" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="workOrderDescription">
                    <el-input type="textarea" v-model="state.editForm.workOrderDescription" :rows="5" :cols="30"></el-input>
                </el-form-item>
                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="updateRow">提交</el-button>
                        <el-button type="plain" @click="state.addDialogVisible = false">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>
        <!-- 编辑工单弹出框 -->
        <el-dialog title="编辑工单信息" v-model="state.editDialogVisible" width="50%" @close="state.editForm = {}">
            <el-form ref="editForm" :model="state.editForm" :rules="state.rules" label-width="80px">
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="工单名称" prop="workOrderName">
                            <el-input v-model="state.editForm.workOrderName"></el-input>
                        </el-form-item>
                    </el-col>

                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="收入" prop="income">
                            <el-input v-model="state.editForm.income"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="处理等级" prop="workOrderLevel">
                            <el-select v-model="state.editForm.workOrderLevel" placeholder="请选择">
                                <el-option v-for="item, index in state.statusList" :key="index" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row v-if="state.activeTab != 1">
                    <el-col :span="12">
                        <el-form-item label="接收人" prop="assignedToUserID">
                            <el-select v-model="state.editForm.assignedToUserID" placeholder="请选择">
                                <el-option v-for="item, index in state.employeeNames" :key="index" :label="item.Name"
                                    :value="item.EmployeeID"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="截止日期" prop="dueDate">
                            <el-date-picker v-model="state.editForm.dueDate" type="date" placeholder="请选择截止日期"
                                @change="changeDate" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item label="备注" prop="workOrderDescription">
                    <el-input type="textarea" v-model="state.editForm.workOrderDescription" :rows="5" :cols="30"></el-input>
                </el-form-item>
                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="updateRow_w">提交</el-button>
                        <el-button type="plain" @click="state.editDialogVisible = false, state.editForm = {}">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog title="工单分配" v-model="state.orderWorkDialogVisible" width="50%" @close="state.orderEditForm = {}">
            <el-form ref="orderEditForm" :model="state.orderEditForm" :rules="state.rules" label-width="80px">
                <el-form-item label="接受人" prop="assignedToUserID">
                    <el-select v-model="state.orderEditForm.assignedToUserID" placeholder="请选择">
                        <el-option v-for="item, index in state.employeeNames" :key="index" :label="item.Name"
                            :value="item.EmployeeID"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="截止日期" prop="dueDate">
                    <el-date-picker v-model="state.orderEditForm.dueDate" type="date" placeholder="请选择截止日期"
                        @change="changeDate" />
                </el-form-item>

                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="addWorkOrder">提交</el-button>
                        <el-button type="plain"
                            @click="state.orderWorkDialogVisible = false, state.orderEditForm = {}">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <el-dialog title="工单审批" v-model="state.approverDialogVisible" width="50%" @close="state.editForm = {}">
            <el-form ref="editForm" :model="state.editForm" :rules="state.rules" label-width="80px">
                <el-form-item label="状态" prop="workOrderStatus">
                    <el-select v-model="state.editForm.workOrderStatus" placeholder="请选择">
                        <el-option v-for="item, index in state.completeStatus" :key="index" :label="item.label"
                            :value="item.value"></el-option>
                    </el-select>
                </el-form-item>

                <el-form-item label="备注" prop="workOrderDescription">
                    <el-input type="textarea" v-model="state.editForm.workOrderDescription" :rows="5" :cols="30"></el-input>
                </el-form-item>

                <el-form-item>
                    <div class="flex justify-between">
                        <el-button type="primary" @click="updateRow_w">提交</el-button>
                        <el-button type="plain"
                            @click="state.approverDialogVisible = false, state.editForm = {}">返回</el-button>
                    </div>
                </el-form-item>
            </el-form>
        </el-dialog>

        <div class="overflow-hidden" :style="{
            'animation': state.drawerStatus ? 'openSearchKey 1s' : 'closeSearchKey 1s',
            'display': state.drawerStatus ? 'block' : 'none'
        }">
            <el-row class=" w-full p-2 flex">
                <el-col :span="18" class="flex items-center">
                    <div class="flex items-center">
                        <div class="text-center w-24">处理等级</div>
                        <el-select placeholder="请选择类型" v-model="state.searchKey.workOrderLevel">
                            <el-option v-for="item in state.statusList" :key="item.value" :label="item.label"
                                :value="item.value"></el-option>
                        </el-select>
                    </div>
                    <div class="ml-4 flex items-center">
                        <div class="text-center  w-20">工单名</div>
                        <el-autocomplete v-model="state.searchKey.workOrderName" @change="inputSearch"
                            :fetch-suggestions="querySearchAsync" placeholder="请输入工单名" @select="handleSelect" class="mr-2">
                            <template #suffix>
                                <el-icon color="#000">
                                    <Search />
                                </el-icon>
                            </template>
                        </el-autocomplete>
                    </div>
                    <div class="ml-4 flex items-center">
                        <div class="text-center  w-20">工单号</div>
                        <el-input placeholder="请输入工单号" v-model="state.searchKey.workOrderNumber"></el-input>
                    </div>
                    <div class="ml-4 flex items-center" v-show="state.activeTab != 4 && state.activeTab != 1">
                        <div class="text-center w-20">状态</div>
                        <el-select placeholder="请选择状态" v-model="state.searchKey.workOrderStatus">
                            <el-option v-for="item in state.completeStatus" :key="item.value" :label="item.label"
                                :value="item.value"></el-option>
                        </el-select>
                    </div>
                    <el-button :icon="Search" type="primary" @click="getTableDate" class="ml-2">搜索</el-button>
                    <el-button :icon="Delete" type="danger" @click="state.searchKey = {}, getTableDate()">重置</el-button>
                </el-col>
                <el-col :span="4" class="flex items-center  ml-2">
                    <el-tooltip :disabled="disabled" content="导入工单数据" placement="bottom" effect="light">
                        <div @click="state.uploadDialogVisible = true" v-if="state.activeTab == 1"
                            class="border p-2 pl-4 pr-4 hover:cursor-pointer hover:bg-blue-300">
                            <el-icon class="el-icon--upload">
                                <Document />
                            </el-icon>
                        </div>
                    </el-tooltip>

                    <el-tooltip :disabled="disabled" content="下载工单模板" placement="bottom" effect="light">
                        <div @click="downloadUser('downLoad')" v-if="state.activeTab == 1"
                            class="border p-2 pl-4 pr-4 hover:cursor-pointer hover:bg-blue-300">
                            <el-icon class="el-icon--upload">
                                <Download />
                            </el-icon>
                        </div>
                    </el-tooltip>

                    <el-tooltip :disabled="disabled" content="新增工单数据" placement="bottom" effect="light">
                        <div @click="state.addDialogVisible = true" v-if="state.activeTab == 1"
                            class="border p-2 pl-4 pr-4 hover:cursor-pointer hover:bg-blue-300">
                            <el-icon class="el-icon--upload">
                                <Plus />
                            </el-icon>
                        </div>
                    </el-tooltip>

                    <el-tooltip :disabled="disabled" content="导出工单数据" placement="bottom" effect="light">
                        <div @click="downloadUser()" class="border p-2 pl-4 pr-4 hover:cursor-pointer hover:bg-blue-300">
                            <el-icon class="el-icon--upload">
                                <Upload />
                            </el-icon>
                        </div>
                    </el-tooltip>
                    <el-tooltip :disabled="disabled" content="批量删除" placement="bottom" effect="light">
                        <div @click="deleteAll" class="border p-2 pl-4 pr-4 hover:cursor-pointer hover:bg-blue-300">
                            <el-icon class="el-icon--upload">
                                <Delete />
                            </el-icon>
                        </div>
                    </el-tooltip>
                </el-col>
            </el-row>
        </div>

        <el-row class="flex justify-center mb-4">
            <div class="rounded-b-2xl w-14 flex justify-center flex-col items-center cursor-pointer"
                @click="state.drawerStatus = !state.drawerStatus">
                <el-icon :class="state.drawerStatus ? '-rotate-90' : 'rotate-90'">
                    <DArrowRight />
                </el-icon>
                <div class=" text-slate-400 text-xs">{{ state.drawerStatus ? '上拉隐藏' : '下拉搜索' }}</div>
            </div>
        </el-row>
        <el-tabs tab-position="left" v-model="state.activeTab" @tab-click="handleTabClick">
            <el-tab-pane :label="item.label" :name="item.value" v-for="item in state.tabList" :key="item.value">
                <TabItem :tableData="state.tableData" :activeTab="state.activeTab" @getSelectedIds="getSelectedIds"
                    @giveWorkOrder="giveWorkOrder" @openUpdata="openUpdata" @openApprover="openApprover"
                    @deleteRow="deleteRow" @getDetail="getDetail">
                </TabItem>
            </el-tab-pane>
            <div class="flex justify-end">
                <el-pagination background @size-change="handleSizeChange_t" @current-change="handleCurrentChange_t"
                    :current-page="state.page.pageNum" :page-sizes="[5, 10]" :page-size="state.page.pageSize"
                    layout="total, sizes, prev, pager, next, jumper" :total="state.page.total" class="mt-6">
                </el-pagination>
            </div>
        </el-tabs>
    </div>
</template>

<script setup>
// import TabItem from './tab-item'
import { useTabsStore } from '../store/store'
import { useRoute } from 'vue-router';
import { onMounted, reactive, ref, computed } from "vue";
import { DeleteFilled, Upload, EditPen, Hide, ZoomIn, Delete, Plus, Search, Download, Lock, DArrowRight, Document } from '@element-plus/icons-vue'
import { taskassignmentDelete, taskassignmentCreate, taskassignmentUpdate } from '../api/taskassignment/taskassignment'
import { formatDate, getAvatarUrl } from '../utils/auth.js'
import { downloadTemplateUser, downloadUserData, analysisExcel } from '../utils/tableMethod.js'
import { findworkOrderByCreate, findworkOrderByOverTime, findoverworkOrderByfinish, findworkOrderByApprover, findworkOrderByReview, findAllWorkOrderList, workorderUpdate, workorderDelete, workorderReadAll, workorderCreate, findWorkOrderAndID } from '../api/workorder/workorder'
const route = useRoute();
const state = reactive({
    editDialogVisible: false,
    addDialogVisible: false,
    orderWorkDialogVisible: false,
    approverDialogVisible: false,
    detailDrawer: false,
    detailData: {},
    selectedIds: [],//选中的id
    drawerStatus: false,//下拉框状态
    tabList: [
        { label: '我创建的', value: 1 },
        { label: '待审核的', value: 2 },
        { label: '我处理的', value: 3 },
        { label: '我完成的', value: 4 },
        { label: '超时的', value: 5 }
    ],
    selectedAssignmentID: [],//选中的分配工单id
    employeeNames: [],
    workorderNames: [],

    searchKey: {
        workOrderNumber: '',//工单号
        workOrderStatus: '',//工单状态
        workOrderLevel: '',//订单处理等级
        workOrderName: '',//搜索框提示词
    },
    tableData: [], //表格数据
    tableDataAll: [], //表格全部不分页数据
    statusList: [
        { label: '较低', value: 1 },
        { label: '一般', value: 2 },
        { label: '紧急', value: 3 },
    ],
    completeStatus: [
        { label: '未完成', value: '0' },
        { label: '已完成', value: '1' },
        { label: '进行中', value: '2' },
    ],
    activeTab: 1,//默认选中第一个tab
    // 受处理工单分页
    page: {
        total: "",
        pageNum: 1,
        pageSize: 5,
    },
    searchType: "exact",//搜索类型
    rules: {
        workOrderName: [
            { required: true, message: '请输入名称', trigger: 'blur' },
        ],
        dueDate: [
            { required: true, message: '请输入截止日期', trigger: 'blur' },
        ],
        workOrderDescription: [
            { required: true, message: '请输入备注', trigger: 'blur' },
        ],
        income: [
            { required: true, message: '请输入预计收入金额', trigger: 'blur' },
        ],
        workOrderLevel: [
            { required: true, message: '请选择工单处理等级', trigger: 'blur' },
        ],
        assignedToUserID: [
            { required: true, message: '请选择接收人', trigger: 'blur' },
        ],
        workOrderStatus: [
            { required: true, message: '请选择工单状态', trigger: 'blur' },
        ]
    },
    orderEditForm: {
        assignedToUserID: '',
        workOrderID: ''
    },
    editForm: {
        assignmentID: '',
        workOrderID: '',
        assignedToUserID: '',
        assignmentDate: '',
        deadline: '',
        income: '',
        workOrderLevel: '',
        workOrderStatus: '',
        workOrderDescription: "",
        workOrderData: {},
        assignedToUserName: {},
        approver: '',//处理人
    },

    // 批量上传
    uploadDialogVisible: false,
    uploadStutas: false,
    // 是否禁用上传
    isUploading: false,
    // 解析后的表格数据
    parseTableData: [],
    parsePage: {
        total: "",
        pageNum: 1,
        pageSize: 5,
    }
})
const orderEditForm = ref()
const editForm = ref()
const addForm = ref()
const useData = useTabsStore()

// 解析日期
const convertExcelDate = (excelDate) =>
{
    const year = Math.floor(excelDate / 365.25) + 1900;
    const month = Math.floor((excelDate % 365.25) / 30.4375) + 1;
    const day = (excelDate % 365.25) % 30.4375 + 1;
    const dateTime = `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day}`;
    return dateTime.slice(0, dateTime.lastIndexOf('.'));
}

// 日期选择
const changeDate = (val) =>
{
    state.orderEditForm.dueDate = formatDate(val)
    state.editForm.dueDate = formatDate(val)
}

// 获取数据
const getTableList = async (apiMethod, params) =>
{
    const requestParams = {
        pageSize: state.page.pageSize,
        pageNum: state.page.pageNum,
        ...state.searchKey,
        ...params
    };
    const result = await apiMethod(requestParams)
    state.page.total = result.data.total
    state.page.pageSize = result.data.pageSize
    state.page.pageNum = result.data.pageNum
    if (state.activeTab != 1) {
        state.tableData = result.data.result.map(element =>
        {
            element.workOrderData.AssignmentID = element.AssignmentID
            element.workOrderData.AssignedToUserID = element.AssignedToUserID
            return element.workOrderData;
        });
        state.tableDataAll = result.data.resultAll.map(element =>
        {
            element.workOrderData.AssignmentID = element.AssignmentID
            element.workOrderData.AssignedToUserID = element.AssignedToUserID
            return element.workOrderData;
        });
    } else {
        state.tableData = result.data.result
        state.tableDataAll = result.data.resultAll
    }
    console.log("获取的数据====》", state.tableData);
}
// 选项卡选择
const handleTabClick = (tab) =>
{
    state.activeTab = tab.paneName
    console.log(state.activeTab);
    state.searchKey = {}
    state.page = {
        total: "",
        pageNum: 1,
        pageSize: 5,
    }
    getTableDate()
}
// 根据选项卡获取数据
const getTableDate = () =>
{
    let params;
    switch (state.activeTab) {
        // 我创建的
        case 1:
            params = { userId: useData.getUserData().userID }
            getTableList(findworkOrderByCreate, params)
            break;
        // 待审核的
        case 2:
            params = { approver: useData.getUserData().userID }
            getTableList(findworkOrderByReview, params)
            break;
        // 我处理的
        case 3:
            params = { approver: useData.getUserData().userID }
            getTableList(findworkOrderByApprover, params)
            break;
        // 我完成的
        case 4:
            params = { userId: useData.getUserData().userID }
            getTableList(findoverworkOrderByfinish, params)
            break;
        // 超时的
        case 5:
            params = { approver: useData.getUserData().userID }
            getTableList(findworkOrderByOverTime, params)
            break;
        default:
            break;
    }
}
// 获取今天日期
const getDay = () =>
{
    let now = new Date();
    let date = now.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit'
    }).replace(/\//g, '-');
    return date;
}
const handleSizeChange_t = (val) =>
{
    state.page.pageSize = val
    state.page.pageNum = 1
    getTableDate()
}
// 分页
const handleCurrentChange_t = (val) =>
{
    state.page.pageNum = val;
    getTableDate()
}
// 打开工单分配窗口
const giveWorkOrder = (val) =>
{
    state.orderWorkDialogVisible = true
    state.editForm = val
}
// 打开详情
const getDetail = (row) =>
{
    state.detailDrawer = true
    state.detailData = row
    console.log(row, "工单信息");
}
// 提交分配工单
const addWorkOrder = async () =>
{
    state.orderEditForm.dueDate = formatDate(state.orderEditForm.dueDate)
    state.orderEditForm.workOrderID = state.editForm.workOrderID
    orderEditForm.value.validate((valid) =>
    {
        if (valid) {
            ElMessageBox.confirm('确定分配工单吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(async () =>
            {
                const res01 = await workorderUpdate(state.editForm)
                const res02 = await taskassignmentCreate(state.orderEditForm)
                if (res01.meta.status == 200 || res02.meta.status == 200) {
                    ElMessage({
                        showClose: true,
                        message: '分配成功',
                        type: 'success',
                    })
                    state.orderWorkDialogVisible = false
                    state.editForm = {}
                    state.orderEditForm = {}
                    getTableDate()
                }
            }).catch(() =>
            {
                ElMessage({
                    showClose: true,
                    message: '已取消',
                    type: 'info',
                })
                state.orderWorkDialogVisible = false
            })
        }
    })
}
// 打开编辑窗口
const openUpdata = (val) =>
{
    state.editForm = val
    state.editDialogVisible = true
}
// 打开审批工单窗口
const openApprover = (val) =>
{
    state.approverDialogVisible = true
    state.editForm = val
}

// 删除
const deleteRow = (row) =>
{
    // 弹出确认删除的对话框
    ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () =>
        {
            if (state.activeTab == 1) {
                // 用户点击确定，执行删除操作
                const res = await workorderDelete({ workOrderID: row.WorkOrderID });
                if (res.meta.status == 200) {
                    // 如果删除操作失败
                    ElMessage({
                        showClose: true,
                        message: '删除成功',
                        type: 'success',
                    });
                } else {
                    ElMessage({
                        showClose: true,
                        message: '删除失败',
                        type: 'error',
                    });
                }
            } else {
                // 用户点击确定，执行删除操作
                const res01 = await taskassignmentDelete({ assignmentID: row.AssignmentID });
                const res02 = await workorderDelete({ workOrderID: row.WorkOrderID });

                if (res01.meta.status == 200 && res02.meta.status == 200) {
                    // 如果删除操作失败
                    ElMessage({
                        showClose: true,
                        message: '删除成功',
                        type: 'success',
                    });
                } else {
                    ElMessage({
                        showClose: true,
                        message: '删除失败',
                        type: 'error',
                    });
                }
                // 删除完成后执行初始化或其他操作
            }
            getTableDate()
        })
        .catch(async () =>
        {
            ElMessage({
                showClose: true,
                message: '已取消',
                type: 'info',
            });
        });
}


// 获取选中的序号
const getSelectedIds = (val, vals) =>
{
    state.selectedIds = val
    state.selectedAssignmentID = vals
}
// 批量删除
const deleteAll = () =>
{
    if (state.selectedIds.length === 0) {
        // 如果没有选择序号，显示提示
        ElMessage({
            showClose: true,
            message: '请选择序号',
            type: 'warning',
        })
    } else {
        // 弹出确认删除的对话框
        ElMessageBox.confirm('确定删除选中的项吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        })
            .then(async () =>
            {
                let deleteStatus = true;
                if (state.activeTab != 1) {
                    // 用户点击确定，执行删除操作
                    let deleteStatus_w = true;
                    let deleteStatus_u = true;
                    for (const item of state.selectedAssignmentID) {
                        const res = await taskassignmentDelete({ assignmentID: item });
                        // 如果删除操作失败
                        if (res.meta.status !== 200) {
                            deleteStatus_u = false;
                            break;  // 停止循环，不再继续删除剩余的项
                        }
                    }

                    for (const item of state.selectedIds) {
                        const res = await workorderDelete({ workOrderID: item });
                        // 如果删除操作失败
                        if (res.meta.status !== 200) {
                            deleteStatus_w = false;
                            break;  // 停止循环，不再继续删除剩余的项
                        }
                    }

                    // 根据删除操作的状态值显示相应的提示
                    if (deleteStatus_u && deleteStatus_w) {
                        ElMessage({
                            showClose: true,
                            message: '删除成功',
                            type: 'success',
                        });
                    } else {
                        ElMessage({
                            showClose: true,
                            message: '删除失败',
                            type: 'error',
                        });
                    }

                    // 删除完成后执行初始化或其他操作
                    getTableDate()
                } else {
                    for (const item of state.selectedIds) {
                        const res = await workorderDelete({ workOrderID: item });
                        // 如果删除操作失败
                        if (res.meta.status !== 200) {
                            deleteStatus = false;
                            break;  // 停止循环，不再继续删除剩余的项
                        } else {
                            // 用户点击确定，执行删除操作
                        }

                    }
                }
                // 根据删除操作的状态值显示相应的提示
                if (deleteStatus) {
                    ElMessage({
                        showClose: true,
                        message: '删除成功',
                        type: 'success',
                    });
                } else {
                    ElMessage({
                        showClose: true,
                        message: '删除失败',
                        type: 'error',
                    });
                }

                // 删除完成后执行初始化或其他操作
                getTableDate()
            })
            .catch(() =>
            {
                ElMessage('已取消')
                // 用户点击取消，不执行任何操作
            });
    }
}
// 修改
const updateRow = () =>
{
    if (state.addDialogVisible) {
        addForm.value.validate((valid) =>
        {
            if (valid) {
                ElMessageBox.confirm('确定新增吗', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () =>
                {
                    console.log(state.editForm, "获取的值");
                    state.editForm.dueDate = formatDate(state.editForm.dueDate)
                    state.editForm.dueDate = formatDate(state.editForm.dueDate)

                    // 当前时间获取赋值
                    state.editForm.createdDate = new Date().toLocaleDateString().replace(/\//g, '-');
                    state.editForm.createdUserID = useData.getUserData().userID
                    const res = await workorderCreate(state.editForm)
                    if (res.meta.status == 200) {
                        ElMessage({
                            showClose: true,
                            message: '新增成功',
                            type: 'success',
                        })
                        state.addDialogVisible = false
                        state.editForm = {}
                        getTableDate()
                    }
                }).catch(() =>
                {
                    ElMessage({
                        showClose: true,
                        message: '已取消',
                        type: 'info',
                    })
                })
            }
        })
    }
}
const updateRow_w = () =>
{
    if (state.editDialogVisible) {
        editForm.value.validate((valid) =>
        {
            if (valid) {
                ElMessageBox.confirm('确定修改吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () =>
                {
                    if (state.activeTab == 2 || state.activeTab == 4) {
                        const res01 = await workorderUpdate(state.editForm)
                        const res02 = await taskassignmentUpdate(state.editForm)
                        if (res01.meta.status == 200 || res02.meta.status == 200) {
                            ElMessage({
                                showClose: true,
                                message: '修改成功',
                                type: 'success',
                            })
                            state.editDialogVisible = false
                            state.editForm = {}
                            getTableDate()
                        }
                    } else {
                        const res01 = await workorderUpdate(state.editForm)
                        if (res01.meta.status == 200) {
                            ElMessage({
                                showClose: true,
                                message: '修改成功',
                                type: 'success',
                            })
                            state.editDialogVisible = false
                            state.editForm = {}
                            getTableDate()
                        }
                    }
                }).catch(() =>
                {
                    ElMessage({
                        showClose: true,
                        message: '已取消',
                        type: 'info',
                    })
                })
            }
        })
    }
    if (state.approverDialogVisible) {
        editForm.value.validate((valid) =>
        {
            if (valid) {
                ElMessageBox.confirm('确定修改吗?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(async () =>
                {
                    const res01 = await workorderUpdate(state.editForm)
                    if (res01.meta.status == 200) {
                        ElMessage({
                            showClose: true,
                            message: '修改成功',
                            type: 'success',
                        })
                        state.approverDialogVisible = false
                        state.editForm = {}
                        getTableDate()
                    }
                }).catch(() =>
                {
                    ElMessage({
                        showClose: true,
                        message: '已取消',
                        type: 'info',
                    })
                })
            }
        })
    }
}



// 查询所有的工单搜索词
const findWorderOrderNames = async () =>
{
    const { workOrderNameList } = await findAllWorkOrderList()
    state.workorderNames = workOrderNameList
    console.log(state.workorderNames, "搜索词")

    state.workorderNames = state.workorderNames.map(function (item)
    {
        return { value: item };
    });
}
// 获取所有的人员名称
const getAllEmployeeNames = async () =>
{
    const { workOrderAndID } = await findWorkOrderAndID()
    state.employeeNames = workOrderAndID
}
//  搜索查找
const inputSearch = () =>
{
    state.searchType = 'fuzzy' //执行模糊搜索
    getTableDate()
}
// 搜索
let timeout
// 触发过滤条件
const querySearchAsync = (queryString, cb) =>
{
    const results = queryString
        ? state.workorderNames.filter(createFilter(queryString))
        : state.workorderNames

    clearTimeout(timeout)
    timeout = setTimeout(() =>
    {
        cb(results)
    }, 3000 * Math.random())
}
// 创建过滤
const createFilter = (queryString) =>
{
    return (restaurant) =>
    {
        return (
            restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0
        )
    }
}
// 搜索框选择
const handleSelect = (item) =>
{
    state.searchKey.workOrderName = item.value
    console.log(state.searchKey.workOrderName, "搜索词")
}


// 下载模板or下载数据表
const downloadUser = async (key) =>
{
    const colsList = [ //设置表格的宽度
        {
            wpx: 50, //序号
        },
        {
            wpx: 100,
        },
        {
            wpx: 100,
        },
        {
            wpx: 50,
        },
        {
            wpx: 200,
        }
    ];

    const positionObj = { start_r: 0, start_c: 0, end_r: 0, end_c: 3 }
    if (key == 'downLoad') {

        const instructions = [
            "导入说明.\n" +
            "1. 请不要改动Excel表结构并严格按照导入规则进行导入,否则将导入失败或出现不可预知的问题.\n" +
            "2. 请勿修改数据表结构，否则将导入失败的注明.\n" +
            "3. 处理级别 1:较低 2:中级 3:紧急"
        ]
        const tableHeader = [
            "序号",
            "工单名称",
            "处理级别",
            "收入",
            "备注"
        ]
        const tableNameTemplate = "工单模板表"
        downloadTemplateUser(instructions, tableHeader, colsList, tableNameTemplate, positionObj)
    } else {
        const tableName = "工单数据表"
        let tabTable = []
        let tableHeader, colsList, positionObj


        if (state.activeTab != 1) {
            tableHeader = [
                "序号",
                "工单号",
                "工单名称",
                "处理级别",
                "状态",
                "收入",
                "创建日期",
                "截止日期",
                "备注",
            ]
            colsList = [ //设置表格的宽度
                {
                    wpx: 50, //序号
                },
                {
                    wpx: 100,
                },
                {
                    wpx: 100,
                },
                {
                    wpx: 50,
                },
                {
                    wpx: 50,
                },
                {
                    wpx: 50,
                },
                {
                    wpx: 150,
                },
                {
                    wpx: 150,
                },
                {
                    wpx: 200,
                }
            ];
            positionObj = { start_r: 0, start_c: 0, end_r: 0, end_c: 7 }
            for (let i = 0; i < state.tableDataAll.length; i++) {
                const item = state.tableDataAll[i];
                tabTable[i] = {
                    WorkOrderID: item.WorkOrderID,
                    OrderNumber: item.OrderNumber,
                    WorkOrderName: item.WorkOrderName,
                    Level: item.Level,
                    Status: item.Status,
                    Income: item.Income,
                    CreatedDate: item.CreatedDate,
                    DueDate: item.DueDate,
                    WorkOrderDescription: item.WorkOrderDescription,
                }
                console.log(item, "===>");
            }


        } else {
            tableHeader = [
                "序号",
                "工单名称",
                "收入",
                "处理级别",
                "备注"
            ]
            colsList = [ //设置表格的宽度
                {
                    wpx: 50, //序号
                },
                {
                    wpx: 100,
                },
                {
                    wpx: 100,
                },
                {
                    wpx: 50,
                },
                {
                    wpx: 200,
                }
            ];
            positionObj = { start_r: 0, start_c: 0, end_r: 0, end_c: 4 }
            for (let i = 0; i < state.tableDataAll.length; i++) {
                const item = state.tableDataAll[i];
                tabTable[i] = {
                    WorkOrderID: item.WorkOrderID,
                    OrderNumber: item.OrderNumber,
                    Level: item.Level,
                    Income: item.Income,
                    WorkOrderDescription: item.WorkOrderDescription,
                }
                console.log(item, "===>");
            }
        }
        let dataRows = tabTable.map(obj => Object.values(obj))
        let titleRow = ['工单数据表']
        console.log("===========>已分配数据", dataRows);
        downloadUserData(tableHeader, titleRow, dataRows, colsList, tableName, positionObj)
    }
}
//上传文件之前的钩子
const beforeUpload = async (file) =>  
{
    const tableJson = await analysisExcel(file)
    state.uploadStutas = true
    console.log(tableJson, "========>1111");
    // 值为空格的参数剔除
    for (let index = 0; index < tableJson.tableData.length; index++) {
        const item = tableJson.tableData[index];
        console.log("===[]", item);
        if (item != '') {
            state.parseTableData[index] = {
                id: item[0],
                workOrderName: item[1],
                income: item[3],
                workOrderLevel: item[2],
                workOrderDescription: item[4],
                createdUserID: useData.getUserData().userID
            }
        }
    }
    state.parsePage.total = state.parseTableData.length
    console.log(state.parseTableData, "=====111===>");
}
const upload = ref()
// 提交上传文件
const submitFileForm = () =>
{
    console.log(state.userTypeNameList, "=======>");
    if (state.uploadStutas) {
        for (let index = 0; index < state.parseTableData.length; index++) {
            state.editForm = state.parseTableData[index];
            console.log(state.editForm, "即将注册的部门数据");
            workorderCreate(state.editForm).then(res =>
            {
                ElMessage({
                    showClose: true,
                    message: '新增成功',
                    type: 'success',
                })
                state.uploadStutas = false
                state.uploadDialogVisible = false
                getTableDate()
            })
        }

    } else {
        upload.value.submit();
    }
}
// 解析数据分页
// 分页
const handleSizeChange = (val) =>
{
    console.log(`每页 ${val} 条`)
    state.parsePage.pageSize = val
}
const handleCurrentChange = (val) =>
{
    console.log(`当前页: ${val}`);
    state.parsePage.pageNum = val;
}
// 计算分页数据
const paginatedData = computed(() =>
{
    const startIndex = (state.parsePage.pageNum - 1) * state.parsePage.pageSize;
    const endIndex = startIndex + state.parsePage.pageSize;
    return state.parseTableData.slice(startIndex, endIndex);
})


onMounted(() =>
{
    getTableDate()
    findWorderOrderNames()
    getAllEmployeeNames()
    const activeTab = route.query.pageNum
    if (activeTab) {
        state.activeTab = activeTab
    }
})
</script>
<style>
@keyframes openSearchKey {
    from {
        height: 0;
        display: none;
    }

    to {
        height: 48px;
        display: block;
    }
}

@keyframes closeSearchKey {
    from {
        height: 48px;
        display: block;
    }

    to {
        height: 0;
        display: none;
    }
}
</style>
